<template>
  <MenuPage
    :data="assetList"
    :columns="assetCol"
    :page.sync="queryParams.pageIndex"
    :size.sync="queryParams.pageSize"
    :total="assetTotal"
    :loading="assetListLoading"
    showSelectTag
    selectName="assetName"
    :selection.sync="selectAssets"
    @queryFun="getAssetList">
    <template slot="search">
      <Button type="primary" ghost class="md-add-jh" @click="creatAsset">创建资产</Button>
      <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />
      <Cascader  change-on-select filterable v-model="assetCategory" :data="assetCategoryList" placeholder="资产类型" style="margin-left: 15px;width: 150px" @on-change="selectAssetTypeChange">
      </Cascader>
      <Select filterable clearable v-model="queryParams.productOwnershipId" @on-change="selectUnit" placeholder="所属单位" style="margin-left: 15px;width: 150px">
        <Option v-for="unit in unitList" :key="unit.id" :value="unit.id">{{unit.name}}</Option>
      </Select>
      <Select filterable clearable v-model="queryParams.vendorId" @on-change="selectIndustry" placeholder="供应商" style="margin-left: 15px;width: 150px">
        <Option v-for="industry in vendorList" :key="industry.id" :value="industry.id">{{industry.name}}</Option>
      </Select>
      <Input v-model.trim="queryParams.name"  clearable placeholder="资产名称" @on-change="searchAssetNameBtn" style="width: 180px;margin-left: 15px" />
      <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshAssetList()">
        <i class="el-icon-refresh-right" />
      </Button>
    </template>
    <!--创建镜像"-->
    <div class="filter-wrap" slot="tagSelect">
        <tag-select
            title="分类标签"
            :current="tagId"
            :data="meshOptionsList"
            style="margin-bottom: 14px;"
            @on-change="changeTag"></tag-select>
    </div>
    <Modal v-model="assetModal" :mask-closable="false" width="600" @on-visible-change="changeVisible" :footer-hide="true" :title="modalTitle">
      <Form ref="assetFormData" :model="assetFormData" :rules="creatAssetRuleValidate" :label-width="120" style="width: 500px">
        <FormItem label="名称" prop="name">
          <div style="display: flex;justify-content: flex-start;width: 580px;">
            <Input  :disabled="!isCreate" v-model.trim="assetFormData.name" placeholder="名称" style="width:380px"></Input>
          </div>
        </FormItem>
        <FormItem label="资产类别" prop="productTypeId" key="productTypeId">
          <Cascader  change-on-select v-model="productTypeIds" :data="assetCategoryList" filterable @on-change="getProductTypeId"></Cascader>
        </FormItem>
        <formItem label="设备类型" prop="deviceType" key="deviceType">
          <Select filterable v-model="assetFormData.deviceType">
              <Option :value="0">虚拟设备</Option>
              <Option :value="1">实物设备</Option>
              <Option :value="2">授权虚拟节点设备</Option>
          </Select>
        </FormItem>
        <FormItem label="分类标签" prop="productTagIdList" key="productTagIdList">
          <products-tag-select-drawer
              v-model="assetFormData.productTagIdList"
              ref="productsTagSelectDrawer"
              @input="changeTags"
              @add-success="getBindMax"
              @update-success="getBindMax"
              @delete-success="deleteSuccess"></products-tag-select-drawer>
        </FormItem>
        <FormItem label="供应商" prop="vendorId" key="vendorId">
          <Select filterable id="formItemVendorId" v-model="assetFormData.vendorId"  filterable @on-change="changeVendor">
            <Option v-for="vendor in vendorList" :value="vendor.id" :key="vendor.id">{{vendor.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="型号" prop="model" key="model">
          <Input id="formItemModel" v-model="assetFormData.model" placeholder="输入型号"></Input>
        </FormItem>
        <FormItem label="是否调研" prop="isSurvey" key="isSurvey">
          <!-- 是否调研：0.未调研、1.已调研 -->
          <RadioGroup id="formItemIsSurvery" v-model="assetFormData.isSurvey">
              <Radio :label="0">未调研</Radio>
              <Radio :label="1">已调研</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="所属单位" prop="productOwnershipId" key="productOwnershipId">
          <Select filterable v-model="assetFormData.productOwnershipId" label-in-value filterable>
            <Option v-for="vendor in unitList" :value="vendor.id" :key="vendor.id">{{vendor.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="描述" prop="description" key="description">
          <Input id="formItemTextarea" type="textarea" v-model="assetFormData.description" placeholder="输入描述"></Input>
        </FormItem>
          <FormItem label="logo" class="ivu-form-item" prop="logo">
            <itemUpload ref="logoUpload"
                        @upload-success="val=>uploadSuccess(val,'logo')"
                        :formatArr="['jpg','png','jpeg']"
                        :showUploadList="true"
                        uploadText="上传logo"
                        @clearFile="setClear('logo')"
                        fileType="files"></itemUpload>
          </FormItem>
          <FormItem  label="白皮书" class="ivu-form-item " prop="whiteBookFileId">
            <itemUpload ref="whiteUpload"
                        @upload-success="val=>uploadSuccess(val,'whiteBook')"
                        :formatArr="['doc','docx','ppt','pdf','pptx']"
                        :showUploadList="true"
                        uploadText="上传白皮书"
                        @clearFile="setClear('whiteBook')"
                        fileType="files"></itemUpload>
          </FormItem>
          <FormItem label="产品手册" class="ivu-form-item " prop="productManualFileId">
            <itemUpload ref="productManualUpload"
                        @upload-success="val=>uploadSuccess(val,'productManual')"
                        :formatArr="['doc','docx','ppt','pdf','pptx']"
                        :showUploadList="true"
                        uploadText="上传手册"
                        @clearFile="setClear('productManual')"
                        fileType="files"></itemUpload>
          </FormItem>
        <FormItem>
          <Button type="primary" @click="submitBtn('assetFormData')" :loading="addAssetBtnLoading" :disabled="setDisabled">确定</Button>
          <Button @click="creatAssetHandleReset('assetFormData')" style="margin-left: 8px">取消</Button>
        </FormItem>
      </Form>
    </Modal>
    <!-- 镜像信息 -->
    <Modal v-model="assetState" title="资产详情" :mask-closable="false" :width="800" footer-hide>
      <div class="item-table">
        <p><span class='label'>资产名称</span><span>{{assetDetailData.name}}</span></p>
        <p><span class='label'>资产类别</span><span>{{assetDetailData.productTypeName}}</span></p>
        <p><span class='label'>设备类型</span><span>{{assetDetailData.deviceType === 0 ? '虚拟设备' : assetDetailData.deviceType === 1 ? '实物设备' : '授权虚拟节点设备'}}</span></p>
        <p><span class='label'>分类标签</span><span>{{assetDetailData.productTagIdList && assetDetailData.productTagIdList.join(',')}}</span></p>
        <p><span class='label'>供应商</span><span>{{assetDetailData.vendorName}}</span></p>
        <p><span class='label'>型号</span><span>{{assetDetailData.model}}</span></p>
        <p><span class='label'>是否调研</span><span>{{assetDetailData.isSurvey === 1 ? '已调研' : '未调研'}}</span></p>
        <p><span class='label'>所属单位</span><span>{{assetDetailData.productOwnershipName}}</span></p>
        <p><span class='label'>描述</span><span>{{assetDetailData.description}}</span></p>
        <p><span class='label'>logo</span><span>
                  <img :src="`/Learn${assetDetailData.logo}`" style="width: auto; height: 40px; vertical-align: middle;" v-if="assetDetailData.logo">
                  <span v-else></span>
        </span></p>
        <p><span class='label'>白皮书</span><span>
           <Tooltip placement="top-start" transfer :max-width="200" :content="assetDetailData.whiteBookName" v-if="assetDetailData.whiteBookPath">
                    <a @click="download(assetDetailData.whiteBookName, assetDetailData.whiteBookPath)">{{ assetDetailData.whiteBookName }}</a>
                  </Tooltip>
                  <span v-else></span>
        </span></p>
        <p><span class='label'>产品手册</span><span>
          <Tooltip placement="top-start" transfer :max-width="200" :content="assetDetailData.productManualName" v-if="assetDetailData.productManualPath">
                    <a @click="download(assetDetailData.productManualName, assetDetailData.productManualPath)">{{ assetDetailData.productManualName }}</a>
                  </Tooltip>
                  <span v-else></span>
        </span></p>
        <p><span class='label'>创建者</span><span>{{assetDetailData.creatorName}}</span></p>
      </div>
    </Modal>
  </MenuPage>
</template>
<script>
import encryption from '@/libs/encryption.js'
import TagSelect from '@/components/tagSelect/tagSelect'
import ProductsTagSelectDrawer from '@/view/testPlatform/asset/products-tag-select-drawer/index.vue';
import { mapState } from 'vuex'
import { validateName128 } from '@/libs/reg'
import * as CommonFn from '../common'
import resourcesReportedMixin from '@/mixin/resources-reported-mixin'
import pageTitle from '@/mixin/pageTitle';
import {getNameUsedV2} from './api/asset'
import {getProductType, getUnitList, getVendorList} from "./logic/assetLogic";
import { getProductUseTag } from '@/view/testPlatform/asset/api/productTag'
import itemUpload from "../components/item-upload/index.vue";
import {queryProductGroupList, deleteProductGroup, addProductGroup, updateProductGroup} from '@/view/testPlatform/asset/api/productGroup.js'
import {getBindMax} from '@/view/testPlatform/asset/api/productTag.js'
export default {
  components: {itemUpload, TagSelect,ProductsTagSelectDrawer},
  mixins: [resourcesReportedMixin,pageTitle],
  data () {
    const isExitString = (rule, value, callback) => {
      if (value) {
        if(!this.isCreate){
          callback()
        }
        getNameUsedV2({name: value}).then(res => {
          if (res.code == 1) {
            if (res.data == 0) {
              callback()
            } else {
              callback(new Error('资产名已被占用'))
            }
          } else {
            callback(new Error(res.message))
          }
        }).catch(err => {
          callback(new Error('网络错误'))
        })
      } else {
        callback()
      }
    }
    return {
      tagId: 'All',
      meshOptionsList: [],
      productManual:{},
      logo:{},
      whiteBook:{},
      unitList:[],
      vendorList:[],
      assetCategoryList:[],
      rangeId: '',
      rangeAllList: [],
      selectAssets: [],
      selectAllImages: false,
      modalTitle: '创建资产',
      assetState: false,
      assetDetailData: {},//详情内容
      queryParams:{
        pageIndex:1,
        pageSize:10
      },
      // 用户信息
      USER_ID: '',
      isRootDesinger: '',
      distributed: false,
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      setTableHei: 'auto',
      showDefImg: false,
      showImgList: false,
      // 镜像列表
      assetListLoading: false,
      assetCategory: [],
      unit: '',
      industry: '',
      assetTotal: 0,
      assetList: [],
      assetCol: [

        {
          title:'资产名称',
          key:'name',
          render:(h,params)=>{
            return h('Tooltip',{
              props:{
                content: params.row.name,
                transfer:true,
                placement: 'bottom-start',
                'max-width': 300
              },
            },[
              h('a',{
                on:{
                  click:()=>{
                    this.$router.push({
                      name: 'assetDetail',
                      query: {
                        name: params.row.name,
                        productId: params.row.id,
                      }
                    })
                  }
                }
              }, params.row.name)
            ])
          }
        },
        {
          title:'资产类型',
          key:'productTypeName'
        },
        {
          title:'供应商名称',
          key:'vendorName'
        },
        {
          title:'所属单位',
          key:'productOwnershipName'
        },
        {
          title:'版本个数',
          key:'versionNum'
        },
        {
          title:'漏洞个数',
          key:'vulNum'
        },
        {
          title:'测试次数',
          key:'testNum'
        },
        {
          title: '操作',
          width: 240,
          slot: 'action',
          opList: [
            {
              txt: '详情',
              on:{
                click:(data,e) => {
                  this.openSystem(data)
                }
              },
            },
            {
              txt: '修改',
              on:{
                click:(data,e) => {
                  this.modifyAsset(data)
                }
              },
            },
            {
              txt: '删除',
              tooltip: true,
              type: 'delete',
              title: '确定要删除这个资产吗？',
              on:{
                click:(data,e) => {
                  this.delAsset(data)
                }
              },
            }
          ]
        }
      ],
      searchImageName: '',
      assetModelInput: '',
      creatByMeModal: false,
      // 创建和修改镜像
      imageID: '',
      assetModal: false,
      updateUrl: `/api/resource-manager/image/add`,
      addAssetBtnLoading: false,
      productTypeIds:[],
      assetFormData: {
        name:'',
        productTypeId:'',
        netinfoId:'',
        deviceType:0,
        productTagIdList: [],
        vendorId:'',
        productOwnershipId: '',
        isSurvey:0,
        imageId:'',
        physicalDeviceCount:'1',
        flavorRef:'',
        model:'',
        version:'',
        description:'',
        logo:'',
        whiteBookFileId:'',
        productManualFileId:''
      },
      creatAssetRuleValidate: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'change' },
          { max: 128, message: '名称长度不能超过128个字符', trigger: 'change' },
          { validator: validateName128, trigger: 'change' },
          { validator:isExitString, trigger: 'blur' }
        ],
        version: [
          { required: true, message: '版本不能为空', trigger: 'blur' },
          {type:'string',max: 64,trigger:'blur',message:'最多输入64个字符'},
        ],
        vendorId: [
          { required: true, message: '请选择商家', trigger: 'change' }
        ],
        productOwnershipId: [
          { required: true, message: '请选择单位', trigger: 'change' }
        ],
        deviceType:[
        {required: true,type:'number', message: '请选择设备类型', trigger: 'change' }
        ],
        isSurvey:[
          {required: true,type:'number', message: '请选择是否调研', trigger: 'change' }
        ],
        productTagIdList: [
          // 龙祥说：罗姐说这里改成非必填项
          // {required: true,type:'array', message: '请选择分类标签', trigger: 'change' }
        ],
        productTypeId:[
          { required: true,message: '请选择资产类别', trigger: 'change' }
        ],
        description: [
          { max: 200, message: '描述长度不能超过200个字符', trigger: 'change' },
        ],
      },
      speed: 0,
      loaded: 0,
      fileSize: 0,
      progress: 0,

      speedWhiteBook: 0,
      loadedWhiteBook: 0,
      fileSizeWhiteBook: 0,
      progressWhiteBook: 0,


      speedManualFileId: 0,
      loadedManualFileId: 0,
      fileSizeManualFileId: 0,
      progressManualFileId: 0,


      setDisabled: false,
      isCreate: true,
      //profile
      profileList: [],
      // 镜像用户
      showImgUser: false,
      formIsShow: false,
      imageUserId: '',
      addUserLoading: false,
      createPort: '22',
      isCreatUser: false,
      isClound: false,
      imgUserList: [],
      flag: 0, //标记成功的次数
      filedArr: [],//承装切片的容器
      oldTime: 0,//初始化时间
      progressflag: false,//控制进度条的展示
      fileName: '',
      saveTargetStatusArr: [],//存储中间状态
      messageSwitch: false,//解决鼠标移入失败或者成功验证状态气泡框位置错乱设置的开关
      systemVersion:[]
    }
  },
  created () {
    // 获取用户id
    let November = sessionStorage.getItem('November')
    November = JSON.parse(encryption.SelfUseDecrypt(November))
    this.USER_ID = November.userId
    this.isRootDesinger = November.isRootDesinger
    this.distributed = November.distributed
    // this.distributedRange = this.$store.state.user.distributedRange
  },
  mounted () {
    let getPage = this.$route.query.page ? parseInt(this.$route.query.page) : 1
    this.queryParams.pageIndex = getPage
    this.getAssetList()
    this.getBindMax()
    getUnitList(this,'unitList');
    getVendorList(this,'vendorList');
    getProductType(this,'assetCategoryList')
  },
  methods: {
    // 当前选中的分类标签被删了，重新选中全部
    deleteSuccess(id) {
      if (this.tagId === id) {
        this.tagId = 'All'
      }
      this.getBindMax()
    },
    changeTags() {
      this.$nextTick(() => {
        this.$refs.assetFormData.validateField('productTagIdList')
      })
    },
    getProductUseTag(id) {
      return new Promise(resolve => {
        if (!id) { // 为创建状态，不需要校验名称唯一性
          resolve([])
          return
        }
        getProductUseTag(id).then(({code, message, data}) => {
          if (code !== 1) {
            this.$Message.warning(message)
            resolve([])
            return
          } else {
            resolve(data || [])
          }
        }).catch(() => {
          resolve([])
        })
      })
    },
    getBindMax() {
      getBindMax({
        pageIndex: 1,
        pageSize: 2147483646
      }).then(({ code, message, data = {} }) => {
        if (code !== 1) {
          this.$Message.warning(message)
          return
        }
        let list = data.items || []
        this.meshOptionsList = list.map(item => {
          return {
            key: item.id,
            value: item.name
          }
        })
      })
    },
    changeTag(val) {
      this.tagId = val
      this.queryParams.productTagId = val === 'All' ? '' : val
      this.queryParams.pageIndex = 1
      this.getAssetList()
    },
    // 隐藏模态框时，重置表单数据
    changeVisible(type) {
      if (!type) {
        this.$refs.assetFormData.resetFields()
        this.productTypeIds = []
        // 延迟200毫秒再修改并重置表单，免得在模态框隐藏动画过程中就出现校验信息，测试又要提bug了
        setTimeout(() => {
          this.$refs.productsTagSelectDrawer && this.$refs.productsTagSelectDrawer.clear()
        }, 200)
      }
    },
    uploadSuccess(val,type){
      this[type]={...val};
      //非必填项，设置表单数据
      if(type=='logo'){
        this.$set(this.assetFormData,'logo',val.filePath)
      }else{
        this.$set(this.assetFormData,type+'Id',val.fileId);
        this.$set(this.assetFormData,type+'FileId',val.fileId);
        this.$set(this.assetFormData,type+'Name',val.fileName);
        this.$set(this.assetFormData,type+'Path',val.filePath);
      }
      //this.$refs.assetFormData.validateField('fileId');
    },
    setClear(key){
      this[key] = {};
      if(key=='logo'){
        this.$set(this.config.data,'logo','')
      }else{
        this.$set(this.assetFormData,key+'Id','');
        this.$set(this.assetFormData,key+'FileId','');
        this.$set(this.assetFormData,key+'Name','');
        this.$set(this.assetFormData,key+'Path','');
      }
    },
    getProductTypeId(val){
      const id =  val.length?val[val.length-1]:'';
      this.assetFormData.productTypeId = id;
      this.$refs.assetFormData.validateField('productTypeId');
    },
    async openSystem (data) { //点击详情的回调
      this.assetDetailData = data;
      let list = await this.getProductUseTag(data.id)
      this.assetDetailData.productTagIdList = list.map(item => item.name)
      this.assetState = true;
    },
    changeVendor(val){
      let obj = this.vendorList.filter(f=>f.id==val)[0];
      if(obj){
        this.assetFormData.vendorName = obj.name;
      }else{
        this.assetFormData.vendorName = '';
      }
    },
    // 镜像列表
    getAssetList (isRefresh) {
      if (!isRefresh) { // 非刷新操作才需要展示等待中的画面
        this.assetListLoading = true
      }
      queryProductGroupList(this.queryParams)
        .then(res => {
          if (res.code == 1) {
            this.assetTotal =res.data.total;
            this.assetList = res.data.items
          }
          this.assetListLoading = false
        })
        .catch(err => {
          this.assetListLoading = false
        })
    },
    searchCreatedByMe (val) {
      this.queryParams.pageIndex = 1
      this.getAssetList()
    },
    searchAssetNameBtn () {
      this.queryParams.pageIndex = 1
      this.getAssetList();
    },
    selectAssetTypeChange (val) {
      this.queryParams.pageIndex = 1;
      this.queryParams.productTypeId = val.length?val[val.length-1]:'';
      this.getAssetList()
    },
    selectUnit () {
      this.queryParams.pageIndex = 1
      this.getAssetList()
    },
    selectIndustry () {
      this.queryParams.pageIndex = 1
      this.getAssetList()
    },
    imageOnChange (val) {
      this.queryParams.pageIndex = val;
      this.getAssetList();
    },
    // 创建镜像的回调
    creatAsset () {
      this.isCreate = true
      this.modalTitle = '创建资产'
      this.assetModal = true
      this.$nextTick(()=>{
        this.$refs.productManualUpload&&this.$refs.productManualUpload.clearFile();
        this.$refs.logoUpload&&this.$refs.logoUpload.clearFile();
        this.$refs.whiteUpload&&this.$refs.whiteUpload.clearFile();
      })

    },
    async modifyAsset (item) { //修改按钮的回调
      this.modalTitle = '修改资产'
      this.isCreate = false;
      this.assetFormData = {...item};
      let list = await this.getProductUseTag(item.id)
      item.productTagIdList = list.map(item => item.id)
      if (item.productTagIdList) {
        this.$refs.productsTagSelectDrawer && this.$refs.productsTagSelectDrawer.getCheckList(list)
      }
      this.assetModal = true
      this.$nextTick(()=>{
        //文件上传特殊处理
        let params = item || {};
        params.productManualPath&&params.productManualName?
          this.$refs.productManualUpload.showDefaultList({fileName:params.productManualName,filePath:params.productManualPath}):
          this.$refs.productManualUpload.showDefaultList(null);
        params.whiteBookPath&&params.whiteBookName?
          this.$refs.whiteUpload.showDefaultList({fileName:params.whiteBookName,filePath:params.whiteBookPath}):
          this.$refs.whiteUpload.showDefaultList(null);
        params.logo?this.$refs.logoUpload.showDefaultList({filePath:params.logo}):
          this.$refs.logoUpload.showDefaultList(null);
      })

      this.productTypeIds = CommonFn.getIdsFromID(this.assetFormData.productTypeId,this.assetCategoryList);

    },
    // 提交镜像
    submitBtn (name) {
      let api = addProductGroup;
      let text = '创建';
      if (this.isCreate) {
        api = addProductGroup;
        text = '创建'
      } else {
        api = updateProductGroup;
        text = '修改'
      }
      let _this = this
      this.$refs[name].validate((valid) => {
        if (valid) {
          let param = {
            ...this.assetFormData
          }
          _this.addAssetBtnLoading = true
          _this.setDisabled = true
          if(_this.isCreate){
            delete param.id;
          }
          api(param).then(res => {
            if (res.code == 1) {
              this.$Message.info(`${text}成功`);
              this.assetModal = false
              this.setDisabled = false
              this.addAssetBtnLoading = false
              this.refreshAssetList()
            }else{
              this.$Message.error(res.message);
            }
          })
            .catch(err => {
              _this.$Message.error('服务器连接失败！')
              _this.addAssetBtnLoading = false
              _this.setDisabled = false
            })
        } else {
          this.$Message.error('请完善信息！');
        }
      })
    },
    creatAssetHandleReset (name) {
      if (this.filedArr.length) {
        this.$Message.warning({ content: '请等待当前文件上传,或者刷新页面重新上传', duration: 5 })
      } else {
        this.progressflag = false
        this.flag = 0 //清空标志位,防止进度条错乱
        this.progress = 0 // 重置进度条
      }
      this.$refs[name].resetFields();
      this.assetModal = false;
    },
    handleUpload (file) {
      this.progressflag = true
      this.flag = 0 //清空标志位,防止进度条错乱
      this.progress = 0 // 重置进度条
      let fileType = this.assetFormData.industry=='kvm'?['qcow2', 'QCOW2']:['TAR', 'tar', 'docker', 'DOCKER']
      // 新加上传过程
      if (file) {
        if (!file.name.includes('.')) {
          this.$Message.error({ content: '请添加文件类型后缀', duration: 5 })
          return false
        }
        let FileExt = file.name.replace(/.+\./, "");//取得文件的后缀名
        let newName = file.name.replace('.' + FileExt, '') //取得文件除了后缀之外的名字
        if (!fileType.includes(FileExt)) {   // 添加上传的镜像文件类型验证
          this.progressflag = false //关闭文件上传进度展示
          this.$Message.error({ content: this.assetFormData.industry=='kvm'?'kvm类型文件格式为 XX.qcow2':'docker类型文件格式为 XX.docker  和 XXX.tar', duration: 5, closable: true })
          return false
        }
        let industry = JSON.parse(JSON.stringify(this.assetFormData.industry))
        if (FileExt == 'qcow2' || FileExt == 'QCOW2') {
          this.assetFormData.industry = 'kvm'
        } else if (FileExt == 'docker' || FileExt == 'DOCKER') {
          this.assetFormData.industry = 'docker'
        }
        if (industry != this.assetFormData.industry) {
          this.assetFormData.osVersion = ''
          this.getImageType()
        }
        let Newfile = new File([file], newName, {
          type: file.type
        })
        if (file.size > 1024 * 1024) {
          this.fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
        } else {
          this.fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'
        }
        this.assetFormData.file = Newfile;
        this.upload(file)
      }

      return false;
    },
    upload (file) {
      if (file.size <= 0) {
        this.$Message.error({
          content: '无效文件!',
          duration: 3
        })
        this.progressflag = false
        return
      }
      this.setDisabled = true //禁用选择文件按钮和提交按钮
      this.filedArr = []
      var clientId = this.generateClientId() //id
      var fileName = file.name;
      var size = file.size
      // if (file.size < 1024 * 1024 * 600) {
      // var shardSize = file.size; //如果上传的文件小于600M直接以当前文件为一个分片
      // } else {
      var shardSize = 1024 * 1024 * 50; //如果上传的文件大于600M就以50M为一个分片
      // }
      var chunks = Math.ceil(size / shardSize); //总片数
      for (var i = 0; i < chunks; ++i) {
        var start = i * shardSize; //计算每一片的起始位置
        var end = Math.min(size, start + shardSize)  //计算每一片的结束位置
        var partFile = file.slice(start, end)
        this.filedArr.push(partFile)
      };
      //上传分片请求函数
      const partUpload = async (clientId, filedArr, fileName, chunks, chunkId) => {
        try {
          let _this = this
          let partFile = filedArr[chunkId]
          var form = new FormData();
          form.append('clientId', clientId); //客户端id
          form.append('file', partFile); // slice方法 用于切出文件的一部分
          form.append('fileName', fileName); // 文件名
          form.append('chunks', chunks); // 总片数
          form.append('chunkId', chunkId); //当前是第几片
          const res = await _this.axios({
            method: 'post',
            url: `${this.baseURL}/resource-manager/upload/part`,
            data: form,
            headers: {
              'Content-type': 'multipart/form-data',
            },
            timeout:0,
            onUploadProgress: progressEvent => {
              if (file.size > 1024 * 1024) {
                this.fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
              } else {
                this.fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'
              }
              this.fileName = file.name
              // if (file.size < 1024 * 1024 * 600) {
              //   var complete = Math.floor(progressEvent.loaded / progressEvent.total * 100)
              //   _this.progress = complete
              // }
              var newTime = +new Date()
              var DTime = (newTime - this.oldTime) / 1000
              this.oldTime = newTime

              var aaspeed = Number(progressEvent.loaded - _this.loaded) / (1024 * 1024)
              _this.loaded = progressEvent.loaded
              if (aaspeed / DTime < 1) {
                _this.speed = (Math.round(aaspeed / DTime * 1024 * 100) / 100).toString() + 'kB/s'
              } else {
                _this.speed = (Math.round(aaspeed / DTime * 100) / 100).toString() + 'MB/s'
              }
            },
          });
          if (res.data.code == 1) {
            chunkId += 1
            if (chunkId < this.filedArr.length) {
              _this.loaded = 0
              this.flag += 1
              var complete = Math.ceil(this.flag / chunks * 100)   //当前进度所占总进度的百分比
              this.progress = complete
              partUpload(clientId, this.filedArr, fileName, chunks, chunkId)
            } else {
              this.flag += 1
              var complete = Math.ceil(this.flag / chunks * 100)   //当前进度所占总进度的百分比
              this.progress = complete
              if (this.progress == 100) {
                this.setDisabled = false //打开提交和选择文件按钮权限
                _this.loaded = 0
                this.speed = 0//置空速度
                this.filedArr = []
                this.$Message.success({
                  content: '文件上传成功!',
                  duration: 3

                })
                // this.mergeFile(clientId,fileName) //不再调用合并分片接口，创建镜像的时候tempId为随机生成的clientId
                this.assetFormData.tempId = clientId
              }
            }
          }
        } catch (error) {
          console.log(error)
        }

      }
      partUpload(clientId, this.filedArr, fileName, chunks, 0)
    },
    //所有文件上传完毕之后的合并接口回调
    mergeFile (clientId, fileName) {
      var formMerge = new FormData();
      formMerge.append("clientId", clientId);
      formMerge.append("fileName", fileName);
      mergeFiles(formMerge)
        .then(res => {
            if (res.data.code == 1) {
              this.assetFormData.tempId = res.data.data
            }
          }
        ).catch(err => {
        this.$Message.error('合并文件出错')
      })
    },
    //文件的唯一ID
    generateClientId () {
      var counter = 0;
      var clientId = (+new Date()).toString(32),
        i = 0;
      for (; i < 5; i++) {
        clientId += Math.floor(Math.random() * 65535).toString(32);
      }
      return clientId + (counter++).toString(32);
    },
    // 删除镜像
    delAsset (item) {
      deleteProductGroup([item.id])
        .then(res => {
          if (res.code == 1) {
            this.$Message.success({
              content: '删除成功！',
              duration: 3,
            })
            if (this.queryParams.pageIndex > 1 && this.assetList.length === 1) {
              this.queryParams.pageIndex -= 1
            }
            this.getAssetList();
          } else {
            this.$Message.error({ content: res.data.message, duration: 5, closable: true })
          }
        })
        .catch(err => {
        })
    },
    // 刷新镜像
    refreshAssetList () {
      this.queryParams = {
        pageIndex:1,
        pageSize:10
      }
      this.assetCategory = []
      this.getAssetList()
    },
    getGb (val) {
      let floatNum = parseInt(val) / (1024 * 1024 * 1024)
      floatNum = floatNum.toFixed(2)
      return floatNum
    },
    // 设置可见范围
    setVisibility (val) {
      let obj = {}
      let text = ''
      let color = ''
      if (val === 'public') {
        text = '系统'
        color = '#4169E1'
      } else if (val === 'share') {
        text = '单位'
        color = '#32CD32'
      } else if (val === 'private') {
        text = '个人'
        color = '#FFA500'
      }
      obj.text = text
      obj.color = color
      return obj
    },
    // 设置是否可点击
    setIsClick (item) {
      if (item.visibility === 'public' || (item.creator !== this.USER_ID && !this.isRootDesinger)) {
        return true //{ 'pointer-events': 'none' }
      }
    },
    setColor (item) {
      let color ='var(--status-pre)';
      switch (item.status) {
        case 'error':  // 创建失败
          color = 'var(--status-no)'//'#ff4242'
          return color
          break;
        case 'create_ing':  // 镜像生成中
          color = 'var(--status-ing)'//'#ff8244'
          return color
          break;
        case 'saving': // 创建中
          color = 'var(--status-ing)';
          return color;
          break;
        case 'active': // 创建成功
          color = 'var(--status-yes)';
          return color;
          break;
        default:
          return color;
      }
    },
    setScriptColor (item) {
      let color = '#ff8244';
      switch (item.verify) {
        case 'none':  // 未验证
          color = 'var(--status-pre)'//'grey'
          return color
          break;
        case 'NONE':  // 未验证
          color = 'var(--status-pre)'//'grey'
          return color
          break;
        case 'verify_ing':  // 开始验证
          color = 'var(--status-ing)'//'#ff8244'
          return color
          break;
        case 'testing':  // 验证中
          color = 'var(--status-ing)'//'#ff8244'
          return color
          break;
        case 'test_complete':  // 验证中
          color = 'var(--status-ing)'//'#ff8244'
          return color
          break;
        case 'active':  // 验证成功
          color = 'var(--status-yes)' //'#06b649'
          return color
          break;
        case 'error':  // 验证失败
          color = 'var(--status-no)'//'#ff4242'
          return color
          break;
      }
    },
    check (item) {
      let id = item.id
      checkImage(id).then((res) => {
        if (res.data.code == 1) {
          this.$Message.success({
            content: '操作成功',
            duration: 3
          })
          this.getAssetList()
        } else {
          this.$Message.warning({
            content: res.data.message,
            duration: 3
          })
        }
      })
    },
    searchItem (val) {
      this.getAssetList();
    },
  },
  beforeDestroy () {

  }
}
</script>
<style scoped>
.item-table {
  display: table;
  width: 100%;
  border: 1px solid #eee;
  table-layout: fixed;
  word-break: break-all;
}
.item-table p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}
.item-table p span {
  display: table-cell;
  border-bottom: 1px solid #eee;
}
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
.filter-wrap /deep/ .item-label.title {
  flex: 0 0 90px !important;
}
</style>
